/*
Version: MPL 1.1/GPL 2.0/LGPL 2.1

The contents of this file are subject to the Mozilla Public License Version 
1.1 (the "License"); you may not use this file except in compliance with 
the License. You may obtain a copy of the License at 
http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.

The Original Code is jsLex - JavaScript profiling injection engine.

The Initial Developer of the Original Code is
Robert Buffone.
Portions created by the Initial Developer are Copyright (C) 2007
the Initial Developer. All Rights Reserved.

Contributor(s):

Robert Buffone

Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
*/

/**
 * The jsLex object is responsible for all information
 * and functionality related to JavaScript profiling.
 */
function jsLex(){}

/**
 * Array to keep track of the function counts
 *
 *  {
 *    index:
 *    count:
 *    totalTime:
 *    callingFunctionArray : [ {
 *            index:
 *            count:
 *            totalTime
 *        }],
 *
 *
 */
jsLex._functionArray = new Array();
jsLex._functionTimeStack = new Array();
jsLex._functionCallStack = new Array();
jsLex._entryFunctions = new Array();
jsLex._entryFunctionsIndex = new Array();
jsLex._profileAppLocation = "../jsLex/profile.html";
jsLex._blockArray = new Array();
jsLex._blockTimeStack = new Array();

/**
 * Variable store the opened profile window
 */
jsLex._profileWindow = null;

/**
 * Variable store this window in.
 */
jsLex._applicationWindow = window;

/**
 * Called inside profiled functions to keep track of the method
 * excution count.
 */
jsLex.incProfile = function(index){
    if (jsLex._functionArray[index] == null){
        jsLex._functionArray[index] = {
            count: 1,
            totalTime: 0
        };
    }else{
        jsLex._functionArray[index].count++;
    }
}

/**
 * Called by the profiler when a function is enter. 
 * Put the arrival time on the stack.
 */
jsLex.enterProfile = function( index ){
    //need to in the function counter.
    jsLex.incProfile(index);

	var timeStack = jsLex._functionTimeStack[index];

    //if the time stack doesn't exist add it
	if (timeStack == null){
		timeStack = new Array();
    	jsLex._functionTimeStack[index] = timeStack;
	}
	
	//add the arrival time to the stack
	timeStack.push(new Date());
}

/**
 * Called when the function is exited. total the time.
 */
jsLex.exitProfile = function( index ){
	var now = new Date();
	var timeStack = jsLex._functionTimeStack[index];	
	if (timeStack == null || timeStack.length == 0) return 0;
	
	var startTime = timeStack.pop();	
	var delta = now.getTime() - startTime.getTime();	
	var totalTime = jsLex._functionArray[index].totalTime;

    //add totalTime to the tracking function object.
	jsLex._functionArray[index].totalTime = totalTime + delta;
	return delta;
}

/**
 * Called when a function is entered and we are tracking the
 * graph structure of the application
 */
jsLex.enterFunctionGraph = function( index ){
    jsLex.enterProfile(index);

	var functionObject = jsLex._functionArray[index];
    if (functionObject.callingFunctionArray == null){
    	var funcLength = jsLex._functionCallStack.length;
        if (funcLength > 0){
            var lastIndex = jsLex._functionCallStack[funcLength - 1];
            functionObject.callingFunctionArray = new Array();
            functionObject.callingFunctionIndexArray = new Array();
            functionObject.callingFunctionArray[lastIndex] = {    
                count: 1,
                index: lastIndex,
	            totalTime: 0
            }
            functionObject.callingFunctionIndexArray.push(lastIndex);
        }else{
            jsLex.addEntryFunction(index);
        }
    }else{
    	var funcLength = jsLex._functionCallStack.length;
        if (funcLength > 0){
            var lastIndex = jsLex._functionCallStack[funcLength - 1];
            var callingObject = functionObject.callingFunctionArray[lastIndex];
            if (callingObject == null){
                functionObject.callingFunctionArray[lastIndex] = {
                    count: 1,
                    index: lastIndex,
		            totalTime: 0
                }
                functionObject.callingFunctionIndexArray.push(lastIndex);
            }else{
                functionObject.callingFunctionArray[lastIndex].count++;    
            }
        }else{
            jsLex.addEntryFunction(index);
        }
    }

    //add this function to the calling stack
    jsLex._functionCallStack.push(index);
}

jsLex.addEntryFunction = function( index ){
    if (jsLex._entryFunctions[index] == null){
        jsLex._entryFunctions[index] = {
            count: 1,
            index: index,
            totalTime: 0
        }
        jsLex._entryFunctionsIndex.push(index);
    }else{
        jsLex._entryFunctions[index].count++;
    }
}

/**
 * Called when a function is exited and we are tracking the
 * graph structure of the application
 */
jsLex.exitFunctionGraph = function( index ){
    totalTime = jsLex.exitProfile(index);

    //pop the last function off of the calling stack
    jsLex._functionCallStack.pop();
    
    arrayLength = jsLex._functionCallStack.length;
    if (arrayLength > 0){
		var functionObject = jsLex._functionArray[jsLex._functionCallStack[arrayLength - 1]];
	    if (functionObject.functionsCalledArray == null){
            functionObject.functionsCalledArray = new Array();
            functionObject.functionsCalledArray[index] = {    
                count: 1,
                index: index,
	            totalTime: totalTime
            }
            functionObject.functionsCalledIndexArray = new Array();
            functionObject.functionsCalledIndexArray.push(index);
	    }else{
            var calledObject = functionObject.functionsCalledArray[index];
            if (calledObject == null){
                functionObject.functionsCalledArray[index] = {
                    count: 1,
                    index: index,
		            totalTime: totalTime
                }
                functionObject.functionsCalledIndexArray.push(index);
            }else{
                functionObject.functionsCalledArray[index].count++;    
                functionObject.functionsCalledArray[index].totalTime+=totalTime;    
            }
	    }
	    
	    //a calling object may not be available becuase this 
	    //function may be an entry function.
		functionObject = jsLex._functionArray[index];
	    if (functionObject != null && functionObject.callingFunctionArray != null){
        	var callingObject = functionObject.callingFunctionArray[jsLex._functionCallStack[arrayLength - 1]];
        	if (callingObject != null){
        		callingObject.totalTime+=totalTime; 
        	}   
        }
    }
}

/**
 *  This function is placed in code to mark the entrance of a native call.
 */
jsLex.enterBlock = function(name){
   	var callFunction = jsLex._blockArray[name];
   	if (callFunction == null){
	   	jsLex._blockArray[name] = {
			count: 1,
			name: name,
			totalTime: 0
		}
	}else{
		callFunction.count++;
	}

	var timeStack = jsLex._blockTimeStack[name];

    //if the time stack doesn't exist add it
	if (timeStack == null){
		timeStack = new Array();
    	jsLex._blockTimeStack[name] = timeStack;
	}
	
	//add the arrival time to the stack
	timeStack.push(new Date());
}

/**
 *  This function is placed in code to mark the exit of a native call.
 */
jsLex.exitBlock = function(name){
	var now = new Date();
	var timeStack = jsLex._blockTimeStack[name];	
	if (timeStack == null || timeStack.length == 0) return;
	
	var startTime = timeStack.pop();	
	var delta = now.getTime() - startTime.getTime();	
	var totalTime = jsLex._blockArray[name].totalTime;

    //add totalTime to the tracking function object.
	jsLex._blockArray[name].totalTime = totalTime + delta;
}

/**
 * Gets the function counter.
 */
jsLex.getFunctionArray = function(){
    return jsLex._functionArray;
}

/**
 * Gets the function counter.
 */
jsLex.getEntryFunctions = function(){
    return jsLex._entryFunctions;
}

/**
 * Gets the function counter.
 */
jsLex.getEntryFunctionsIndex = function(){
    return jsLex._entryFunctionsIndex;
}

/**
 * Gets the block array.  These are the hand code blocks.
 */
jsLex.getBlocks = function(){
    return jsLex._blockArray;
}

/**
 * Get the location of the profile window.
 */
jsLex.getProfileAppLocation = function(){
    return jsLex._profileAppLocation;
}

jsLex.setProfileAppLocation = function(location){
    jsLex._profileAppLocation = location;
}

/**
 * Listen for key board events. If the keyboard event 
 * is a Ctrl+j then open the profile window.
 */
jsLex.keyOpenProfileWindow = function(location){
	if (location != null){
		jsLex._profileAppLocation = location;
	}
	document.onkeydown = function(e){
		if(!e){
			//for IE
			e = window.event;
	   	}
	   	if(e.keyCode==74 && e.ctrlKey == true && e.altKey == true){
	      	//keyCode 74 is j key
	      	jsLex.openProfileWindow();
	   	} 	
	}
	
}

/**
 * Gets the function counter.
 */
jsLex.openProfileWindow = function(location){
    if (location == null){
        location = jsLex._profileAppLocation;
    }
    
    //keep track of the windows
    jsLex._profileWindow = window.open(location, '_new'); //, 'width=720,height=500,resize=yes');
    jsLex._profileWindow.applicationWindow = window;
    jsLex._profileWindow.jsLexFunctionArray = jsLex.getFunctionArray();
    jsLex._profileWindow.jsLexEntryFunctions = jsLex.getEntryFunctions();
    jsLex._profileWindow.jsLexEntryFunctionsIndex = jsLex.getEntryFunctionsIndex();
    jsLex._profileWindow.jsLexBlocks = jsLex.getBlocks();
      
    //--------------------------------------------------------------------
    //setup any 3rd party performance monitors    
    //Check to see if we are working with dojo profiling and integrate it.
    if((typeof dojo!="undefined") && (typeof dojo.profile!="undefined")){
   		jsLex._profileWindow.dojoProfile = dojo.profile._profiles;
    }
}

/**
 * Get Xml format of the Navigator information.
 */
jsLex.getNavigatorInfo = function(){
    var  infoXml = "<browserInfo>" + 
        "<info name=\"location\">"+window.applicationWindow.location+"</info>"+
        "<info name=\"appCodeName\">"+navigator.appCodeName+"</info>"+
        "<info name=\"appMinorVersion\">"+navigator.appMinorVersion+"</info>"+
        "<info name=\"appName\">"+navigator.appName+"</info>"+
        "<info name=\"appVersion\">"+navigator.appVersion+"</info>"+
        "<info name=\"cookieEnabled\">"+navigator.cookieEnabled+"</info>"+
        "<info name=\"cpuClass\">"+navigator.cpuClass+"</info>"+
        "<info name=\"javaEnabled\">"+navigator.javaEnabled()+"</info>"+
        "<info name=\"language\">"+navigator.language+"</info>"+
        "<info name=\"onLine\">"+navigator.onLine+"</info>"+
        "<info name=\"opsProfile\">"+navigator.opsProfile+"</info>"+
        "<info name=\"oscpu\">"+navigator.oscpu+"</info>"+
        "<info name=\"platform\">"+navigator.platform+"</info>"+
        "<info name=\"product\">"+navigator.product+"</info>"+
        "<info name=\"productSub\">"+navigator.productSub+"</info>"+
        "<info name=\"securityPolicy\">"+navigator.securityPolicy+"</info>"+
        "<info name=\"systemLanguage\">"+navigator.systemLanguage+"</info>"+
        "<info name=\"userAgent\">"+navigator.userAgent+"</info>"+
        "<info name=\"userLanguage\">"+navigator.userLanguage+"</info>"+
        "<info name=\"userProfile\">"+navigator.userProfile+"</info>"+
        "<info name=\"vendor\">"+navigator.vendor+"</info>"+
        "<info name=\"vendorSub\">"+navigator.vendorSub+"</info>"+
    "</browserInfo>";  
    return infoXml;
}

